package com.smart.sso.server.controller.admin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
//import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
//import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smart.mvc.config.ConfigUtils;
import com.smart.mvc.exception.ValidateException;
import com.smart.mvc.model.Pagination;
import com.smart.mvc.model.Result;
import com.smart.mvc.model.ResultCode;
import com.smart.mvc.util.StringUtils;
import com.smart.mvc.validator.Validator;
import com.smart.mvc.validator.annotation.ValidateParam;
import com.smart.sso.server.common.LoginUser;
import com.smart.sso.server.controller.common.BaseController;
import com.smart.sso.server.enums.TrueFalseEnum;
import com.smart.sso.server.log.SystemControllerLog;
import com.smart.sso.server.model.Role;
import com.smart.sso.server.model.User;
import com.smart.sso.server.model.UserRole;
import com.smart.sso.server.model.LoginIPLimit;	//add by YM
import com.smart.sso.server.model.LoginDatetimeLimit;	//add by YM
import com.smart.sso.server.provider.PasswordProvider;
import com.smart.sso.server.service.RoleService;
import com.smart.sso.server.service.UserGroupService;
import com.smart.sso.server.service.UserRoleService;
import com.smart.sso.server.service.UserService;
import com.smart.sso.server.util.OperationUtils;
import com.smart.sso.server.service.LoginIPLimitService;	//add by YM
import com.smart.sso.server.service.LoginDatetimeLimitService;	//add by YM

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;

/**
 * @author Joe
 */
@Api(tags = "用户管理")
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	@Resource
	private UserRoleService userRoleService;
	@Resource
	private UserGroupService userGroupService;
	@Resource
	private LoginIPLimitService loginIPLimitService;
	@Resource
	private LoginDatetimeLimitService loginDatetimeLimitService;

	@ApiOperation("初始页")
	@RequestMapping(method = RequestMethod.GET)
	public String execute(Model model) {
		return "/admin/user";
	}

	@ApiOperation("新增/修改页")
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	@SystemControllerLog(operationId = OperationUtils.operation_user_add ,description = "新增用户")
	public String edit(@ApiParam(value = "id") Integer id, Model model , HttpServletRequest request) {
		User user;
		
		if (id == null) {
			user = new User();
			model.addAttribute("ipLimitList", null);	//add by YM
			model.addAttribute("datetimeLimitList", null);	//add by YM
		}
		else {
			user = userService.get(id);
			model.addAttribute("ipLimitList", getIpLimitList(id));	//add by YM
//			model.addAttribute("datetimeLimitList", getDatetimeLimitList(id));	//add by YM
			model.addAttribute("dateLimitList", getDateLimitList(id));	//add by YM
			model.addAttribute("timeLimitList", getTimeLimitList(id));	//add by YM
		}
		model.addAttribute("user", user);
		
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");
		List<UserRole> userRole = userRoleService.findByUserRoleId(loginUser.getUserId(), null);
		int roleId = userRole.get(0).getRoleId();
		model.addAttribute("roleList", getRoleList(id , roleId));
		return "/admin/userEdit";
	}

	@ApiOperation("列表")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public @ResponseBody Result list(
			@ApiParam(value = "登录名") String account,	//account是""
			@ApiParam(value = "开始页码", required = true) @ValidateParam({ Validator.NOT_BLANK }) Integer pageNo,
			@ApiParam(value = "显示条数", required = true) @ValidateParam({ Validator.NOT_BLANK }) Integer pageSize,
			HttpServletRequest request) {
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");
		List<UserRole> userRole = userRoleService.findByUserRoleId(loginUser.getUserId(), null);
		int roleId = userRole.get(0).getRoleId();
		int userId = userRole.get(0).getUserId();
		if(userId == 1)
			return Result.createSuccessResult().setData(userService.findPaginationByAccount(null, new Pagination<User>(pageNo, pageSize)));
		else {
			ArrayList<Role> subRoles = (ArrayList<Role>) roleService.findPaginationByName(null, roleId, new Pagination<Role>(pageNo, pageSize)).getList();
			ArrayList<User> users = new ArrayList<User>();
			for(int i=0 ; i < subRoles.size() ; i++) {
				ArrayList<UserRole> userRoles = (ArrayList<UserRole>) userRoleService.findByUserRoleId(null, subRoles.get(i).getId()); 
				for(int j=0 ; j< userRoles.size(); j++) {
					User user = userService.get(userRoles.get(i).getUserId());
					users.add(user);
				}
			}
			Pagination<User> pagination =new Pagination<User>(pageNo , pageSize);
			pagination.setList(users);
			pagination.setRowCount(users.size());
			return Result.createSuccessResult().setData(pagination);
		}
	}

	@ApiOperation("验证登录名")
	@RequestMapping(value = "/validateAccount", method = RequestMethod.POST)
	public @ResponseBody Result validateAccount(
			@ApiParam(value = "id") Integer id,
			@ApiParam(value = "登录名", required = true) @ValidateParam({ Validator.NOT_BLANK }) String account) {
		Result result = Result.createSuccessResult();
		User user = userService.findByAccount(account);
		if (null != user && !user.getId().equals(id)) {
			result.setCode(ResultCode.ERROR).setMessage("登录名已存在");
		}
		return result;
	}

	@ApiOperation("启用/禁用")
	@RequestMapping(value = "/enable", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_user_enable , description = "启用用户")
	public @ResponseBody Result enable(
			@ApiParam(value = "ids", required = true) @ValidateParam({ Validator.NOT_BLANK }) String ids,
			@ApiParam(value = "是否启用", required = true) @ValidateParam({ Validator.NOT_BLANK }) Boolean isEnable) {
		List<Integer> idList = getAjaxIds(ids);
		if(isEnable == true) {
			for(int i=0 ; i<idList.size() ; i++) {
				List<UserRole> userRoles = userRoleService.findByUserRoleId(idList.get(i), null);
				if( userRoles ==null || userRoles.size()==0)
					return Result.createSuccessResult().setMessage("有用户无角色，请先授予角色");
			}
		}
		userService.enable(isEnable, getAjaxIds(ids));
		return Result.createSuccessResult();
	}

	@ApiOperation("新增/修改提交")
	@ApiResponse(response = Result.class, code = 200, message = "success")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_user_edit , description="修改用户")
	public @ResponseBody Result save(
			@ApiParam(value = "id") Integer id,
			@ApiParam(value = "登录名", required = true) @ValidateParam({ Validator.NOT_BLANK }) String account,
			@ApiParam(value = "密码 ") String password,
			@ApiParam(value = "是否启用", required = true) @ValidateParam({ Validator.NOT_BLANK }) Boolean isEnable,
			@ApiParam(value = "角色ids") String roleIds,
			@ApiParam(value = "允许访问的IP范围") String ips,
			@ApiParam(value = "允许访问的日期范围") String dateTimes,
			@ApiParam(value = "允许访问的时段范围") String times,
			@ApiParam(value = "用户CPU限额") Integer cpuLimit,
			@ApiParam(value = "用户内存限额") Integer memLimit,
			@ApiParam(value = "用户带宽限额") Integer bandwidthLimit) {
		User user;
//		LoginIPLimit loginIPLimit ;	//add by ym
		if (id == null) {
			if (StringUtils.isBlank(password)) {
				throw new ValidateException("密码不能为空");
			}
			user = new User();
			user.setCreateTime(new Date());
//			loginIPLimit = new LoginIPLimit();	//add by ym
		}
		else {
			user = userService.get(id);
		}
		user.setAccount(account);
		if (StringUtils.isNotBlank(password)) {
			user.setPassword(PasswordProvider.encrypt(password));
		}
		user.setIsEnable(isEnable);
		user.setCpuLimit(cpuLimit);
		user.setMemLimit(memLimit);
		user.setBandwidthLimit(bandwidthLimit);
		userService.save(user, getAjaxIds(roleIds));
		
		loginIPLimitService.deleteById(Arrays.asList(user.getId()));	//清空之前的数据
		loginIPLimitService.save(user.getId(), ips);	//保存用户输入的IP数据
		
		loginDatetimeLimitService.deleteById(Arrays.asList(user.getId()));	//清空之前的数据
		loginDatetimeLimitService.saveDateTimes(user.getId(), dateTimes);	//保存用户输入的日期数据
		loginDatetimeLimitService.saveTimes(user.getId(), times);	//保存用户输入的时段数据
		
		return Result.createSuccessResult();
	}

	@ApiOperation("重置密码")
	@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_user_resetPassword , description = "重置密码")
	public @ResponseBody Result resetPassword(
			@ApiParam(value = "ids", required = true) @ValidateParam({ Validator.NOT_BLANK }) String ids) {
		userService.resetPassword(PasswordProvider.encrypt(ConfigUtils.getProperty("system.reset.password")), getAjaxIds(ids));
		return Result.createSuccessResult();
	}

	@ApiOperation("删除")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_user_delete ,description = "删除用户")
	public @ResponseBody Result delete(
			@ApiParam(value = "ids", required = true) @ValidateParam({ Validator.NOT_BLANK }) String ids) {
		List<Integer> idList = getAjaxIds(ids);
		for(int i=0 ; i < idList.size() ; i++) {
			if(idList.get(i) == 1) {
				idList.remove(i);
				return Result.createSuccessResult().setMessage("禁止删除超级管理员");
			}
		}
		userService.deleteById(idList);
		userRoleService.deleteByUserIds(idList);
		userGroupService.deleteByUserIds(idList);
		return Result.createSuccessResult();
	}
	
	//获得当前角色的子角色（admin可以获得全部角色)
	private List<Role> getRoleList(Integer userId , int pid) {
		List<Role> list = roleService.findByAll(TrueFalseEnum.TRUE.getValue() , pid);
		if (userId != null) {
			for (Role role : list) {
				List<UserRole> userRole = userRoleService.findByUserRoleId(userId, role.getId());
				if (null != userRole && userRole.size()>0) {
					role.setIsChecked(true);
				}
				else {
					role.setIsChecked(false);
				}
			}
		}
		return list;
	}
	
	private List<LoginIPLimit> getIpLimitList(Integer userId) {
		List<LoginIPLimit> list = loginIPLimitService.findByUserId(userId);
		return list;
	}
	
	private List<LoginDatetimeLimit> getDatetimeLimitList(Integer userId) {
		List<LoginDatetimeLimit> list = loginDatetimeLimitService.findByUserId(userId);
		return list;
	}
	
	private List<LoginDatetimeLimit> getDateLimitList(Integer userId) {
		List<LoginDatetimeLimit> tmpList = loginDatetimeLimitService.findByUserId(userId);
		List<LoginDatetimeLimit> list = new ArrayList<LoginDatetimeLimit>();
		for(int i=0, len=tmpList.size(); i<len; i++)
		{
			LoginDatetimeLimit loginDatetimeLimit = tmpList.get(i);
			if(!loginDatetimeLimit.getIsTime())
			{
				list.add(loginDatetimeLimit);
			}
		}
		return list;
	}
	
	private List<LoginDatetimeLimit> getTimeLimitList(Integer userId) {
		List<LoginDatetimeLimit> tmpList = loginDatetimeLimitService.findByUserId(userId);
		List<LoginDatetimeLimit> list = new ArrayList<LoginDatetimeLimit>();
		for(int i=0, len=tmpList.size(); i<len; i++)
		{
			LoginDatetimeLimit loginDatetimeLimit = tmpList.get(i);
			if(loginDatetimeLimit.getIsTime())
			{
				list.add(loginDatetimeLimit);
			}
		}
		return list;
	}
}